﻿using System;
using JdSoft.Apple.Apns.Notifications;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace WSOAMOBIMIDWARE
{
    public class PushNotificationService
    {
        /// <summary>
        /// 推送服务方法应用
        /// </summary>
        public static string pushIOSNotifications(List<PNMessage> messages)
        {
            //设置传入数据
            StringBuilder errorSb = new StringBuilder();

            //true为使用测试环境，false为正式环境
            bool sandbox = false;

            //开发者测试证书
            string p12File = "MobileOASandBox.p12";

            //开发者证书密码
            string p12FilePassword = "XmWellSoft302#)@";
            //string p12FilePassword = "WELLsoft123*";

            //Actual Code starts below:
            //--------------------------------

            string p12Filename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p12File);

            NotificationService service = new NotificationService(sandbox, p12Filename, p12FilePassword, 1);

            service.SendRetries = 1; //5 retries before generating notificationfailed event
            service.ReconnectDelay = 5000; //5 seconds

            service.Error += new NotificationService.OnError(service_Error);
            service.NotificationTooLong += new NotificationService.OnNotificationTooLong(service_NotificationTooLong);

            service.BadDeviceToken += new NotificationService.OnBadDeviceToken(service_BadDeviceToken);
            service.NotificationFailed += new NotificationService.OnNotificationFailed(service_NotificationFailed);
            service.NotificationSuccess += new NotificationService.OnNotificationSuccess(service_NotificationSuccess);
            service.Connecting += new NotificationService.OnConnecting(service_Connecting);
            service.Connected += new NotificationService.OnConnected(service_Connected);
            service.Disconnected += new NotificationService.OnDisconnected(service_Disconnected);

            for (int i = 0; i < messages.Count; i++)
            {
                Notification alertNotification = new Notification(messages[i].receiverDeviceToken);

                //通知内容
                alertNotification.Payload.Alert.Body = cutIOSStr(messages[i].content);
                alertNotification.Payload.AddCustom("content", new object[] { cutIOSStr(messages[i].content) });
                alertNotification.Payload.AddCustom("url", new object[] { messages[i].url });
                alertNotification.Payload.AddCustom("username", new object[] { messages[i].username });

                //声音
                alertNotification.Payload.Sound = "default";

                //Queue the notification to be sent
                if (!service.QueueNotification(alertNotification))
                {
                    errorSb.Append(messages[i].username);
                    errorSb.Append(": 发送失败！");
                }
            }

            service.Close();
            service.Dispose();

            return errorSb.ToString();
        }

        public static string cutIOSStr(string msg)
        {
            if (string.IsNullOrEmpty(msg))
                return string.Empty;
            StringBuilder result = new StringBuilder();
            int totalLen = 0;
            for(int i = 0;i<msg.Length;i++){
                int tmpLen = 0;
                if ((int)msg[i] > 127)
                {
                    tmpLen = 3;
                    if (totalLen + tmpLen > 48)
                    {

                        if (i == msg.Length - 1)
                        {
                            result.Append(msg[i]);
                        }
                        else
                        {
                            if (totalLen + tmpLen == 49)
                            {
                                result.Append(msg[i] + "...");
                            }
                            else
                            {
                                result.Append("...");
                            }
                        }
                        break;
                    }
                    else
                    {
                        totalLen += tmpLen;
                        result.Append(msg[i]);
                    }
                }
                else
                {
                    tmpLen = 1;
                    if (totalLen + tmpLen > 48)
                    {
                        if (i == msg.Length - 1)
                        {
                            result.Append(msg[i]);
                        }
                        else
                        {
                            result.Append(msg[i]);
                            result.Append("...");
                            break;
                        }
                    }
                    else
                    {
                        totalLen += tmpLen;
                        result.Append(msg[i]);
                    }
                }
            }
            return result.ToString();
        }
        /// <summary>
        /// 推送服务方法应用
        /// </summary>
        public static string pushAndroidNotifications(string serverUrl, List<PNMessage> messages)
        {
            //设置传入数据
            StringBuilder errorSb = new StringBuilder();

            for (int i = 0; i < messages.Count; i++)
            {
                string url = "http://" + serverUrl + "/notification.do?action=send&broadcast=N&username=" + messages[i].receiverDeviceToken + "&title=新的消息&message=" + messages[i].content + "&uri=" + messages[i].url.Replace("&", "%26");
                HttpResponse response = HttpRequest(url, "GET", null, Encoding.UTF8);

                if (!response.exeFlag)
                {
                    errorSb.Append(messages[i].username);
                    errorSb.Append(": " + response.message);
                }
            }

            return errorSb.ToString();
        }
        
        static void service_BadDeviceToken(object sender, BadDeviceTokenException ex)
        {
            Console.WriteLine("Bad Device Token: {0}", ex.Message);
        }

        static void service_Disconnected(object sender)
        {
            Console.WriteLine("Disconnected...");
        }

        static void service_Connected(object sender)
        {
            Console.WriteLine("Connected...");
        }

        static void service_Connecting(object sender)
        {
            Console.WriteLine("Connecting...");
        }

        static void service_NotificationTooLong(object sender, NotificationLengthException ex)
        {
            Console.WriteLine(string.Format("Notification Too Long: {0}", ex.Notification.ToString()));
        }

        static void service_NotificationSuccess(object sender, Notification notification)
        {
            Console.WriteLine(string.Format("Notification Success: {0}", notification.ToString()));
        }

        static void service_NotificationFailed(object sender, Notification notification)
        {
            Console.WriteLine(string.Format("Notification Failed: {0}", notification.ToString()));
        }

        static void service_Error(object sender, Exception ex)
        {
            Console.WriteLine(string.Format("Error: {0}", ex.Message));
        }

        /// <summary>
        /// 发送Http请求
        /// </summary>
        public static HttpResponse HttpRequest(string url, string method, string postData, Encoding encoding)
        {
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Stream requestStream = null;
            Stream responseStream = null;
            StreamReader streamReader = null;
            byte[] bytes = null;
            string returnStr = string.Empty;
            HttpResponse httpResponse;

            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);


                //以下是发送的http头，随便加，其中referer挺重要的，有些网站会根据这个来反盗链  

                //禁止重定向
                request.AllowAutoRedirect = false;

                //保持连接
                request.KeepAlive = true;

                //上面的http头看情况而定，但是下面俩必须加  
                request.ContentType = "application/x-www-form-urlencoded";

                //提交请求方式
                request.Method = method;
                if (!string.IsNullOrEmpty(postData))
                {
                    //postDataStr即为发送的数据  
                    bytes = encoding.GetBytes(postData);
                    request.ContentLength = bytes.Length;

                    //初始化请求数据流
                    requestStream = request.GetRequestStream();
                    requestStream.Write(bytes, 0, bytes.Length);
                }

                //获取返回数据
                response = (HttpWebResponse)request.GetResponse();
                responseStream = response.GetResponseStream();

                //将返回数据解析为字符串
                streamReader = new StreamReader(responseStream, encoding);
                returnStr = streamReader.ReadToEnd();

                httpResponse = new HttpResponse(true, response.Headers.Get("Set-Cookie"), returnStr);
            }
            catch (Exception e)
            {
                httpResponse = new HttpResponse(false, e.Message);
            }
            finally
            {
                bytes = null;
                returnStr = string.Empty;
                //关闭连接
                if (streamReader != null) streamReader.Close();
                if (responseStream != null) responseStream.Close();
                if (requestStream != null) requestStream.Close();
            }
            return httpResponse;
        }
    }
}
